package com.mall.action;

import com.github.pagehelper.PageInfo;
import com.mall.bean.ItemCat;
import com.mall.service.CatsService;
import com.mall.uitl.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/CatsController")
public class CatsController {

    @Autowired
    CatsService catsService;
    //   bookName:"",
    //    bookType:"",
    //    currentPage:1
    @RequestMapping(value = "/queryCats",params = {"cat_name"})
    public JsonUtil queryCats(ItemCat itemCat, Integer currentPage){
        PageInfo<ItemCat> pageInfo =  catsService.queryDataByPage(currentPage,5,itemCat);

        JsonUtil jsonUtil = new JsonUtil();
        jsonUtil.setData(pageInfo);

        return jsonUtil;
    }

    @RequestMapping(value = "/updateCats")
    public JsonUtil updateCats(@Validated ItemCat catBean, BindingResult bindingResult){
        List<FieldError> fieldErrorList =  bindingResult.getFieldErrors();


        JsonUtil jsonUtil = new JsonUtil();

        if (fieldErrorList.size()>0){
            StringBuilder stringBuilder = new StringBuilder();
            for(FieldError error:fieldErrorList){
                /// System.out.println("字段:"+error.getField() +"校验未通过:"+error.getDefaultMessage());
                stringBuilder.append("字段").append(error.getField()).append("校验未通过").append(error.getDefaultMessage()).append("   ");

            }
            jsonUtil.setMsg(stringBuilder.toString());
            jsonUtil.setCode(1);
        }else{
            catsService.update(catBean);
        }

        return  jsonUtil;
    }

    @RequestMapping(value = "/deleteCats")
    public JsonUtil deleteCats(ItemCat itemCat){
        itemCat.setCat_deleted(false);
        int update = catsService.update(itemCat);

        JsonUtil jsonUtil = new JsonUtil();
        if(update > 0){
            jsonUtil.setCode(0);
            jsonUtil.setMsg("删除成功");
        }else{
            jsonUtil.setCode(1);
            jsonUtil.setMsg("删除失败");
        }

        return  jsonUtil;
    }

    @RequestMapping(value = "/insertCats")
    public JsonUtil insertCats(ItemCat itemCat){
        itemCat.setCat_deleted(true);
        int update = catsService.insert(itemCat);

        JsonUtil jsonUtil = new JsonUtil();
        if(update > 0){
            jsonUtil.setCode(0);
            jsonUtil.setMsg("添加成功");
        }else{
            jsonUtil.setCode(1);
            jsonUtil.setMsg("添加失败");
        }

        return  jsonUtil;
    }
}
